const router = require('express').Router();
const multer  = require('multer');
const path = require('path');
// 定义一个上传的实例
// 先定义上传的目的地和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads')
  },
  // 每一次上传都会触发
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    // cb 第二个参数定义文件名
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname))
  }
})

const upload = multer({ storage: storage })

// 显示上传文件页面
router.get('/upload', (req, res) => {
  res.render('upload')
})

// 上传文件
router.post('/upload', upload.single('file'), (req, res) => {
  /* 
    req.file
    /static/uploads/上传成功文件名
  */
  
  res.send({
    code: 0,
    msg: '上传成功',
    data: {
      url: '/static/uploads/' + req.file.filename
    }
  })
})


module.exports = router;